﻿/*
===========================================================================

  Copyright (c) 2010-2014 Darkstar Dev Teams

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see http://www.gnu.org/licenses/

  This file is part of DarkStar-server source code.

===========================================================================
*/

#ifndef _CHARENTITY_H
#define _CHARENTITY_H

#include "../../common/cbasetypes.h"
#include "../../common/mmo.h"

#include <map>
#include <list>
#include <deque>

#include "battleentity.h"
#include "../item_container.h"
#include "../linkshell.h"
#include "petentity.h"
#include "automatonentity.h"

#include "../recast_container.h"
#include "../latent_effect_container.h"
#include "../trade_container.h"
#include "../treasure_pool.h"
#include "../merit.h"
#include "../instance.h"
#include "../universal_container.h"
#include "../utils/itemutils.h"

// Quest Areas
enum QUESTAREA
{
	QUESTS_SANDORIA		= 0,
	QUESTS_BASTOK		= 1,
	QUESTS_WINDURST		= 2,
	QUESTS_JEUNO		= 3,
	QUESTS_OTHER		= 4,
	QUESTS_OUTLANDS		= 5,
	QUESTS_AHTURHGAN	= 6,
	QUESTS_CRYSTALWAR	= 7,
	QUESTS_ABYSSEA		= 8,
	QUESTS_ADOULIN		= 9,
	QUESTS_COALITION	= 10
};

#define MAX_QUESTAREA    11
#define MAX_QUESTID     256
#define MAX_MISSIONAREA  13
#define MAX_MISSIONID    95

struct jobs_t
{
	uint32 unlocked;				// битовая маска профессий, доступных персонажу (первый бит - дополнительная профессия) Bitmask of professions available to the characters (the first bit - additional job)
	uint8  job[MAX_JOBTYPE];		// текущий уровень для каждой из профессий Current level for each of the professions
	uint16 exp[MAX_JOBTYPE];		// текущее количество опыта для каждой из профессий Current amount of experience for each profession
	uint8  genkai;					// максимальный уровень профессий персонажа Maximum # of character professions
};


struct event_t
{
	int32 EventID;                  // номер события Number of event
    int32 Option;                   // фиктивный возвращаемый результат Dummy return value

    CBaseEntity* Target;            // инициатор события Initiator of the event

	string_t Script;                // путь к файлу, отвечающему за обработку события Path to the file is responsible for handling events
	string_t Function;              // не используется Not used

	void reset()
    {
		EventID = -1;
        Option  =  0;
        Target  =  0;
		Script.clear();
		Function.clear();
	}
};

struct profile_t
{
	uint8	   nation;			// принадлежность к государству Nation of alliegence
	uint8	   mhflag;			// флаг выхода из MogHouse Flag out of MogHouse
	uint16	   title;			// звание Title of Character
	uint16     fame[5];			// известность Fame total
	uint8 	   rank[3];			// рагн в трех государствах Rank in the three nations
	uint32	   rankpoints;	    // очки ранга в трех государствах Rank points in three nations
	location_t home_point;		// точка возрождения персонажа Character home point
};


struct expChain_t
{
	uint16 chainNumber;         // Experience chain #
	uint32 chainTime;           // Timer for Experience Chain to expire
};

struct NationTP_t
{
	uint32		sandoria;
	uint32		bastok;
	uint32		windurst;
	uint32		ahturhgan;
	uint32		maw;
	uint32		pastsandoria;
	uint32		pastbastok;
	uint32		pastwindurst;
};


struct PetInfo_t
{
	bool		respawnPet;		// Used for spawning pet on zone
	uint8		petID;			// ID as in wyvern(48), carbuncle(8) ect..
	PETTYPE		petType;		// Type of pet being transfered
	int32		petHP;			// Pets HP
	float		petTP;			// Pets TP
};

struct AuctionHistory_t
{
	uint16		itemid; // Item ID of object
	uint8		stack;  // Stack size of objects
	uint32		price;  // Price of object
	uint8		status; //e.g. if sold/not sold/on market
};

struct UnlockedAttachments_t
{
	uint8 heads;            // Automaton Heads
	uint8 frames;           // Automaton Frames
	uint32 attachments[8];  // Automaton Attachments
};

struct GearSetMod_t
{
	uint8	modNameId;      // Modifier Name
	uint16	modId;          // Modifier ID
	uint16	modValue;       // Modifier value
};

struct currency_t
{
    union
    {
        struct
        {
            uint32 sandoriacp, bastokcp, windurstcp;
        };
        uint32 conquestpoints[3];
    };
    union
    {
        struct
        {
            uint16 beastmanseal, kindredseal, kindredcrest, hkindredcrest, skindredcrest;
        };
        uint16 seals[5];
    };
    uint16 ancientbeastcoins;
    uint16 valorpoints, scylds;
    union
    {
        struct
        {
            uint32 fishingpoints, woodworkingpoints, smithingpoints, goldsmithingpoints, weavingpoints, leatherpoints, bonepoints, alchemypoints, cookingpoints;
        };
        uint32 guildpoints[9];
    };
    uint32 cinders;
    union
    {
        struct
        {
            uint8 firefewell, icefewell, windfewell, earthfewell, lightningfewell, waterfewell, lightfewell, darkfewell;
        };
        uint8 fewell[8];
    };
    uint32 ballistapoints, fellowpoints;
    union
    {
        struct
        {
            uint16 chocobuckssandoria, chocobucksbastok, chocobuckswindurst;
        };
        uint16 chocobucks[3];
    };
    uint32 researchmarks;
    union
    {
        struct
        {
            uint8 tunnelworms, morionworms, phantomworms;
        };
        uint8 meeblesworms[3];
    };
    uint32 moblinmarbles;
    uint16 infamy, prestige;
    uint32 legionpoints, sparksofeminence, shiningstars, imperialstanding;
    union
    {
        struct
        {
            uint32 lsanctumassault, mjtgassault, lcavernassault, periqiaassault, ilrusiatollassault, nyzultokens;
        };
        uint32 assaultpoints[6];
    };
    uint32 zeni, jettons, therionichor, alliednotes, bayld;
    uint16 kineticunits, unknown;
    uint32 obsidianfragments;
    uint16 lebondoptwings, pulchridoptwings;
    uint32 mweyaplasm, cruor, resistancecredits, dominionnotes;
    union
    {
        struct
        {
            uint8 fifthechtrophies, fourthechtrophies, thirdechtrophies, secondechtrophies, firstechtrophies;
        };
        uint8 echelontrophies[5];
    };
    uint8 cavepoints, idtags, opcredits;
    uint32 traverserstones, voidstones, kupofriedcorundums;
    uint8 imprimaturs, pheromonesacks;
};

/************************************************************************
*                                                                       *
*                                                                       *
*                                                                       *
************************************************************************/

class CBasicPacket;

typedef std::deque<CBasicPacket*> PacketList_t;
typedef std::map<uint32,CBaseEntity*> SpawnIDList_t;
typedef std::vector<EntityID_t> BazaarList_t;

class CCharEntity : public CBattleEntity
{
public:

	jobs_t					jobs;							// доступрые профессии персонажа Occupations of character
	keyitems_t				keys;							// таблица ключевых предметов Table of key items
	event_t					m_event;						// структура для запуска событый Structure to trigger events
	skills_t				RealSkills;						// структура всех реальных умений персонажа, с точностью до 0.1 и не ограниченных уровнем Structure of the real skills of the character, up to 0.1, and not limited to the level of
	nameflags_t				nameflags;						// флаги перед именем персонажа Flags in front of the name of the character
	profile_t				profile;						// профиль персонажа (все, что связывает города и персонажа) Character profile (everything that connects the city and the character)
	expChain_t				expChain;						// Exp Chains
	search_t				search;							// данные и комментарий, отображаемые в окне поиска Data and comments are displayed in the search box
	bazaar_t				bazaar;							// все данные, необходимые для таботы bazaar All the data necessary for bazaar
	uint16					m_EquipFlag;					// текущие события, обрабатываемые экипировкой (потом упакую в структуру, вместе с equip[]) Current events that are handled gear (then pack them in a structure with equip [])
    uint16					m_EquipBlock;					// заблокированные ячейки экипировки Locked cells of equipment
	bool					m_EquipSwap;					// True if equipment was recently changed
	uint8					equip[17];						// SlotID where equipment is
	uint8					equipLoc[17];					// ContainerID where equipment is

	uint8					m_ZonesList[36];				// список посещенных персонажем зон List of zones visited by the character
	uint8					m_SpellList[128];				// список изученных заклинаний List learned spells
    uint8					m_TitleList[94];				// список заслуженных завний List of honored titles
	uint8					m_Abilities[46];				// список текущих способностей List of current abilities
	uint8					m_LearnedAbilities[46];			// learnable abilities (corsair rolls) Learnable abilities (corsair rolls)
	uint8					m_TraitList[16];				// список постянно активных способностей в виде битовой маски List of active traits in the form of a bit mask
    uint8					m_PetCommands[32];				// список доступных команд питомцу List of available commands for pets
	uint8					m_WeaponSkills[32];
	questlog_t				m_questLog[MAX_QUESTAREA];		// список всех квестов List of all quests
	missionlog_t			m_missionLog[MAX_MISSIONAREA];	// список миссий List of missions
	assaultlog_t			m_assaultLog;					// список assault миссий List of assault missions
	campaignlog_t			m_campaignLog;					// список campaing миссий List of campaign missions
    uint32					m_rangedDelay;					// Ranged attack delay (with timestamp for repeat attacks, hence 32bit)for items, abilities and magic
	uint32					m_lastBcnmTimePrompt;			// The last message prompt in seconds
	PetInfo_t				petZoningInfo;					// Used to repawn a Dragoon's pets ect on zone
	void					resetPetZoningInfo();			// Reset pet zoning info (when changing job ect)
	uint8					m_SetBlueSpells[20];			// The 0x200 offsetted blue magic spell IDs which the user has set. (1 byte per spell)

	UnlockedAttachments_t	m_unlockedAttachments;			// Unlocked Automaton Attachments (1 bit per attachment)
    CAutomatonEntity*       PAutomaton;                     // Automaton statistics

	// Эти миссии не нуждаются в списке пройденных, т.к. клиент автоматически
	// отображает более ранние миссии выплненными
    // These missions do not need a list passed as client automatically
    // Displays the earlier mission

	uint16			  m_copCurrent;					// Current mission Chains of Promathia
	uint16			  m_acpCurrent;					// Current mission A Crystalline Prophecy
	uint16			  m_mkeCurrent;					// Current mission A Moogle Kupo d'Etat
	uint16			  m_asaCurrent;					// Current mission A Shantotto Ascension

    // TODO: половина этого массива должна храниться в char_vars, а не здесь, т.к. эта информация не отображается в интерфейсе клиента и сервер не проводит с ними никаких операций
    // TODO: half of the array should be stored in char_vars, and not here, because This information is not displayed in the interface of the client and the server does not perform any operations with them

    currency_t        m_currency;                   // Conquest points, imperial standing points etc
	NationTP_t        nationtp;						// Supply tp, runic portal, campaign tp,...

    uint8             GetGender();                  // узнаем пол персонажа Find out the sex of the character

	int32			  firstPacketSize();            // размер первого пакета в PacketList Size of the first packet in PacketList
    void              clearPacketList();            // отчистка PacketList Cleanup PacketList
    void              pushPacket(CBasicPacket*);    // добавление копии пакета в PacketList Add up package PacketList
	bool			  isPacketListEmpty();          // проверка размера PacketList Size check for PacketList
	CBasicPacket*	  popPacket();                  // получение первого пакета из PacketList Get the first package of PacketList
                                                    
    CLinkshell*       PLinkshell;                   // linkshell, в которой общается персонаж Linkshell, in which a character can talk
	CTreasurePool*	  PTreasurePool;                // сокровища, добытые с монстров Treasure, obtained from monsters
    CMeritPoints*     PMeritPoints;                 // Merit points your character has to spend
	bool              MeritMode;                    // If true then player is meriting

    CRecastContainer* PRecastContainer;             // Container for Recast timers (Spells, Abilities, etc)

	CLatentEffectContainer* PLatentEffectContainer; // Container for Latent Effects

	CItemContainer*   PGuildShop;					// текущий магазин гильдии, в котором персонаж производит закупки Store the current guilds, in which the characters make purchases
	CItemContainer*	  getStorage(uint8 LocationID);	// получение указателя на соответствующее хранилище Get a pointer to the appropriate storage

    CTradeContainer*  TradeContainer;               // Container used specifically for trading.
	CTradeContainer*  Container;                    // универсальный контейнер для обмена, синтеза, магазина и т.д. Universal container for the exchange, synthesis, shop etc.
	CUContainer*	  UContainer;					// новый универсальный контейнер для обмена, синтеза, магазина и т.д. New universal container for the exchange, synthesis, shop etc.
    CTradeContainer*  CraftContainer;               // Container used for crafting actions.

	CBaseEntity*	  PWideScanTarget;				// wide scane цель Widescan Target

	SpawnIDList_t	  SpawnPCList;					// список видимых персонажей List of visible characters
	SpawnIDList_t	  SpawnMOBList;					// список видимых монстров List of visible MOBs
	SpawnIDList_t	  SpawnPETList;					// список видимых питомцев List of visible PETs
	SpawnIDList_t	  SpawnNPCList;					// список видимых npc List of visible NPCs
                                                    
	void			  SetName(int8* name);			// устанавливаем имя персонажа (имя ограничивается 15-ю символами) Set the character's name (the name is limited to 15-th character)
                                                    
    EntityID_t        TradePending;                 // ID персонажа, предлагающего обмен ID character's Swap
	EntityID_t        InvitePending;                // ID персонажа, отправившего приглашение в группу ID of the character who sent the invitation to the party
    EntityID_t        BazaarID;                     // Pointer to the bazaar we are browsing.
	BazaarList_t      BazaarCustomers;              // Array holding the IDs of the current customers

	uint32			  m_InsideRegionID;				// номер региона, в котором сейчас находится персонаж (??? может засунуть в m_event ???) Number of the region, which now houses the character (can shove m_event???)
	uint8			  m_LevelRestriction;			// ограничение уровня персонажа Limit the level of a character
    uint16            m_Costum;                     // карнавальный костюм персонажа (модель) Carnival costume character (model)
	uint16            m_Monstrosity;                // Monstrosity model ID
	uint32            m_AHHistoryTimestamp;         // Timestamp when last asked to view history
    uint32            m_DeathCounter;               // Counter when you last died. This is set when you first login
    uint32            m_DeathTimestamp;             // Timestamp when death counter has been saved to database

    uint8             m_PVPFlag;                    // PVP Flag
	uint8			  m_hasTractor;					// checks if player has tractor already Checks if player has tractor already
	uint8			  m_hasRaise;					// checks if player has raise already Checks if player has raise already
    uint8             m_hasAutoTarget;              // возможность использования AutoTarget функции The use of the function AutoTarget
	position_t		  m_StartActionPos;				// позиция начала действия (использование предмета, начало стрельбы, позиция tractor)
                                                    // Start position of the (use of the item, the ranged attack started, the position of tractor)

	uint32            m_PlayTime;
	uint32            m_SaveTime;

    uint32            m_LastYell;

	uint8             m_GMlevel;                    // Level of the GM flag assigned to this character
    bool              m_isGMHidden;                 // GM Hidden flag to prevent player updates from being processed.

    uint8             m_mentor;                     // Mentor flag status.
    bool              m_isNewPlayer;                // New player flag..
    bool              m_LanFlag;                    // True if character is LAN flagged

	int8              getShieldSize();              // Return size of equipped shield

	bool              getWeaponSkillKill();                             // Get the WeaponSkillKill flag
	void              setWeaponSkillKill(bool isWeaponSkillKill);       // Set the WeaponSkillKill flag
	bool              getMijinGakure();                                 // Get the MijinGakure flag
	void              setMijinGakure(bool isMijinGakure);               // Set the MijinGakure flag
	bool              getStyleLocked();
	void              setStyleLocked(bool isStyleLocked);

	bool			  isRapidShot;										// Flag to track rapid shot
	bool			  secondDoubleShotTaken;							// Flag to track number of double shots taken
    bool              isDoubleShot;                                     // Flag to track if it's a double shot
    bool              isQuickMagic;                                     // Flag to track if you proced Quick Magic

    bool              isWeaponUnlocked(uint16 indexid);                 // Return if weapon is unlocked
    bool              addWsPoints(uint8 points, uint16 WeaponIndex);    // Add points for a weaponskill
    UnlockedWeapons_t unlockedWeapons[MAX_UNLOCKABLE_WEAPONS];          // Chars unlocked weapon status

	int16 addTP(int16 tp) override;                 // Add Technical Points
	int32 addHP(int32 hp) override;                 // Add Hit Points
	int32 addMP(int32 mp) override;                 // Add Mana Points

	std::vector<GearSetMod_t> m_GearSetMods;		// The list of gear set mods currently applied to the character.
    std::vector<AuctionHistory_t> m_ah_history;		// AH history list (в будущем нужно использовать UContainer in the future to use UContainer)

	void SetPlayTime(uint32 playTime);				// Set playtime
	uint32 GetPlayTime(bool needUpdate = true);     // Get playtime

    CItemArmor* getEquip(SLOTTYPE slot);

	 CCharEntity();									// конструктор Designer
	~CCharEntity();									// деструктор Destructor

private:

    CItemContainer*    m_Inventory;
    CItemContainer*    m_Mogsafe;
    CItemContainer*    m_Storage;
    CItemContainer*    m_Tempitems;
    CItemContainer*    m_Moglocker;
    CItemContainer*    m_Mogsatchel;
    CItemContainer*    m_Mogsack;
    CItemContainer*    m_Mogcase;
    CItemContainer*    m_Wardrobe;

	bool			m_isWeaponSkillKill;            // Check if this was a WeaponSkill induced death.
	bool			m_isMijinGakure;                // Check if this was a Mijin Gakure induced death.
	bool            m_isStyleLocked;

	PacketList_t      PacketList;					// в этом списке хранятся все пакеты, предназначенные для отправки персонажу
                                                    // This list contains all of the packages to be sent character
};

#endif
